package com.ztp.pc.gui.gtabpane;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.HashMap;
import javax.swing.JPanel;

import com.ztp.pc.gui.gtabpane.GTabButton.TabButtonActionListener;

public class GTabPane extends JPanel {
	
	private static int cardId = 0;
	
	private GTabHeader tabHeader;
	private JPanel cardPanel;
	private CardLayout cardLayout;
	private HashMap<String, Component> cards = new HashMap<String, Component>();
	
	public GTabPane(){
		
		this.setLayout(new BorderLayout(0,0));
		
		tabHeader = new GTabHeader();
		cardLayout = new CardLayout(0,0);
		cardPanel = new JPanel();
		cardPanel.setLayout(cardLayout);
		
		
		this.add(tabHeader, BorderLayout.NORTH);
		this.add(cardPanel, BorderLayout.CENTER);
		//debug();
	}
	
	
	///--------PUBLIC METHODS
	
	public void addCtrlComponent(Component comp){
		tabHeader.addCtrlComponent(comp);
	}
	
	public void addCard(Component comp, String title){
		String compId = "card_"+cardId++;
		cards.put(compId, comp);
		cardPanel.add(comp, compId);
		
		GTabButton gtb = new GTabButton(title, compId);
		gtb.addTabBtnActionListener(tbsl);
		tabHeader.addTabButton(gtb);
	}
	
	public Component removeCard(int index){
		return null;
	}
	
	void addExistingCardAt(Component comp, GTabButton gtb, int index){
		cards.put(gtb.getLinkedCardId(), comp);
		cardPanel.add(comp, gtb.getLinkedCardId(), index);	
		gtb.addTabBtnActionListener(tbsl);
		tabHeader.addTabButtonAt(gtb, index);
	}
	
	Component removeCard(String linkedCompId){
		Component delComp = cards.get(linkedCompId);
		cardPanel.remove(delComp);
		cards.remove(linkedCompId);
		tabHeader.removeTabButton(linkedCompId).removeTabBtnActionListener(tbsl);
		return delComp;
	}
	
	
	//------------Listeners
	
	private TabButtonActionListener tbsl = new TabButtonActionListener() {
		
		@Override
		public void onSelect(GTabButton gtb, String  linkedCompId) {
			cardLayout.show(cardPanel, linkedCompId);
 		}
		
		@Override
		public void onClose(GTabButton gtb, String linkedCompId) {
			cardPanel.remove(cards.get(linkedCompId));
			cards.remove(linkedCompId);
			//System.out.println("cardPanel " + cardPanel.getComponents().length);
		}
	};
	
	public void debug(){
		cardPanel.setBackground(Color.black);
		//tabHeader.setBackground(Color.GRAY);
		
		MouseMotionListener tabPaneMouseListener = new MouseMotionListener() {
			@Override
			public void mouseMoved(MouseEvent e) {
			}
			
			@Override
			public void mouseDragged(MouseEvent e) {
				Point p = e.getPoint();
				Component c = GTabPane.this.getComponentAt(p);
				//System.out.println("GtabPane "+p + " " + ((c != null)?c.toString():"c null"));
			}
		};
		this.addMouseMotionListener(tabPaneMouseListener);
	}
	
}
